package lagou.gateway.lagougateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    private static final String TOKEN = "token";

    private static Set<String> urls=new HashSet<>();
    static {
        urls.add("/EMAILSERVER/sendEmail");
        urls.add("/USERSERVER/verifyAndInsert");
        urls.add("/USERSERVER/login");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
         ServerHttpRequest request = exchange.getRequest();
         URI uri = request.getURI();
         String path = uri.getPath();
         if (!urls.contains(path)){
             String token = findToken(exchange);
             if (StringUtils.isBlank(token)){
                 if (StringUtils.isBlank(token)) {
                     String url = "http://www.test.com/login.html";
                     ServerHttpResponse response = exchange.getResponse();
                     //303状态码表示由于请求对应的资源存在着另一个URI，应使用GET方法定向获取请求的资源
                     response.setStatusCode(HttpStatus.SEE_OTHER);
                     response.getHeaders().set(HttpHeaders.LOCATION, url);
                     return response.setComplete();
                 }
             }
         }else {

         }

        return chain.filter(exchange);
    }


    private String findToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        for (Map.Entry<String, List<HttpCookie>> stringListEntry : cookies.entrySet()) {
            String key = stringListEntry.getKey();
            List<HttpCookie> value = stringListEntry.getValue();
            for (HttpCookie httpCookie : value) {
                String name = httpCookie.getName();
                if (TOKEN.equals(name)) {
                    return httpCookie.getValue();
                }
            }
        }

        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
